package top.techqi.app.mcs51.usbdlk.tile

import android.hardware.usb.UsbDevice
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import top.techqi.app.mcs51.databinding.ItemUsbdlkListPortBinding
import top.techqi.usbd.UsbDriver
import top.techqi.usbd.driver.serial.BasicsSerialDriver
import top.techqi.view.recyclerview.tile.BindHolder
import top.techqi.view.recyclerview.tile.TilePortion
import top.techqi.view.recyclerview.tile.TileRecord

class UsbdlkListPortPortion(
    private val interaction: Interaction
) : TilePortion<
        UsbdlkListPortPortion.Holder,
        UsbdlkListPortPortion.Record>() {
    override fun onMakeHolder(inflater: LayoutInflater, container: ViewGroup): Holder {
        val holder = Holder(inflater, container)
        holder.binding.imbUsbdlkListPortUart.setOnClickListener {
            val record = holder.record ?: return@setOnClickListener
            interaction.onUartClick(record)
        }
        return holder
    }

    override fun onBindRecord(holder: Holder, record: Record) {
        holder.binding.txtUsbdlkNameValue.text = record.name
        val driver = record.driver
        if (BasicsSerialDriver::class.java.isAssignableFrom(driver)) {
            holder.binding.imbUsbdlkListPortUart.visibility = View.VISIBLE
        } else {
            holder.binding.imbUsbdlkListPortUart.visibility = View.GONE
        }
    }

    data class Record private constructor(
        val intfId: Int,
        val name: String,
    ) : TileRecord {
        override val index: String
            get() = "${device.deviceName}/$name"

        lateinit var device: UsbDevice
            private set
        lateinit var driver: Class<out UsbDriver>
            private set

        constructor(
            device: UsbDevice,
            driver: Class<out UsbDriver>,
            intfId: Int,
            name: String,
        ) : this(intfId, name) {
            this.device = device
            this.driver = driver
        }
    }

    class Holder(inflater: LayoutInflater, container: ViewGroup) :
        BindHolder<Record, ItemUsbdlkListPortBinding>(
            inflater, container, ItemUsbdlkListPortBinding::inflate
        )

    interface Interaction {
        fun onUartClick(record: Record)
    }
}
